package com.cashmama.market.api.application.controller.notify;

import com.alibaba.fastjson.JSON;
import com.cashmama.market.api.application.annos.SignIgnore;
import com.cashmama.market.api.application.annos.VisitorAccessible;
import com.cashmama.market.api.domain.enums.PayNotifyCodeEnum;
import com.cashmama.market.api.domain.service.NotifyService;
import com.cashmama.market.api.domain.vo.order.repayment.RePayResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: market-api
 * @description Algo360回调
 * @author: frank
 * @create: 2020-01-08 10:28
 **/
@Controller
public class Algo360Controller {

    private static final Logger LOGGER = LoggerFactory.getLogger(Algo360Controller.class);

    @Autowired
    private NotifyService notifyService;

    @SignIgnore
    @VisitorAccessible
    @RequestMapping(value = "/hook/algo360", method = RequestMethod.POST)
    @ResponseBody
    public void hookAlgo360(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        try {
            notifyService.notifyAlgo360(request);
        } catch (Exception e) {
            write(response, PayNotifyCodeEnum.FAILD);
            LOGGER.error("Hook Algo360: 异步通知报文解析异常:", e);
            return;
        }
        write(response, PayNotifyCodeEnum.SUCCESS);
    }

    private void write(HttpServletResponse response, PayNotifyCodeEnum payNotifyCodeEnum) throws Exception {

        RePayResultInfo payResponse = new RePayResultInfo();
        payResponse.setRetCode(payNotifyCodeEnum.getCode());
        payResponse.setRetMsg(payNotifyCodeEnum.getDesc());
        response.getWriter().write(JSON.toJSONString(payResponse));
        response.getWriter().flush();
    }
}
